package com.doit.day02;


import com.alibaba.fastjson.JSON;

import java.sql.*;
import java.util.Iterator;

public class MysqlIterator implements Iterator<String> {
    private ResultSet resultSet;

    public MysqlIterator() throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        PreparedStatement pps = conn.prepareStatement("select * from user_info");
        resultSet = pps.executeQuery();
    }


    @Override
    public boolean hasNext() {
        boolean flag = false;
        try {
            flag =  resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }


    @Override
    public String next() {
        int id = 0;
        String name = null;
        int age = 0;
        String gender = null;
        try {
            id = resultSet.getInt("id");
            name = resultSet.getString("name");
            age = resultSet.getInt("age");
            gender = resultSet.getString("gender");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        UserInfo userInfo = new UserInfo(id, name, age, gender);
        String json = JSON.toJSONString(userInfo);
        return json;
    }
}
